package com.wjh.garbagetype.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wjh.garbagetype.constant.Url;
import com.wjh.garbagetype.entity.GarbageType;
import com.wjh.garbagetype.enums.HttpCodeEnum;
import com.wjh.garbagetype.exception.GarbageTypeException;
import com.wjh.garbagetype.mapper.GarbageTypeMapper;
import com.wjh.garbagetype.result.GarbageTypeResult;
import com.wjh.garbagetype.result.Result;
import com.wjh.garbagetype.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * @Description 实现类
 * @Date 2020/4/17 18:04
 * @Created by jiahui.wu
 */
@Service
public class GarbageTypeServiceImpl implements GarbageTypeService {

    private static final Logger logger = LoggerFactory.getLogger(GarbageTypeServiceImpl.class);

    @Autowired
    private HttpRequestService httpRequestService;

    @Autowired
    private GarbageTypeMapper garbageTypeMapper;

    /**
     *  请求参数key
     */
    private static final String PARAM_KEY = "key";

    /**
     *  请求参数img
     */
    private static final String PARAM_IMG = "img";

    /**
     *  请求垃圾分类接口响应参数
     */
    private static final String CODE = "code";

    /**
     *  请求垃圾分类接口响应参数
     */
    private static final String NEW_LIST = "newslist";

    /**
     *  逻辑处理
     * @param file
     * @return
     */
    @Override
    public Result garbageType(MultipartFile file) {
        // 将图片转成base64
        String imgBase64Str = FileUtils.fileTransformationBase64(file);
        // 设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 设置参数
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>(2);
        params.add(PARAM_KEY, Url.API_KEY);
        params.add(PARAM_IMG, imgBase64Str);
        String responseResult;
        try {
            responseResult = httpRequestService.postRequest(Url.GARBAGE_TYPE_URL, httpHeaders, params);
            logger.info("请求垃圾分类接口-响应数据为={}", responseResult);
        } catch (Exception e) {
            return Result.error(HttpCodeEnum.ERROR.getCode(), HttpCodeEnum.ERROR.getMessage());
        }
        if (StringUtils.isEmpty(responseResult)) {
            return Result.error(HttpCodeEnum.RESULT_NULL.getCode(), HttpCodeEnum.RESULT_NULL.getMessage());
        }
        JSONObject parseObject = JSON.parseObject(responseResult);
        // 请求响应code, 200为成功
        String code = parseObject.get(CODE) == null ? null : parseObject.get(CODE).toString();
        // 判断是否请求垃圾分类接口成功
        if (!HttpCodeEnum.SUCCESS.getCode().toString().equals(code)) {
            throw new GarbageTypeException("请求垃圾分类接口code响应不成功， code=" + code);
        }
        String dataStr = parseObject.get(NEW_LIST) == null ? null : parseObject.get(NEW_LIST).toString();
        JSONArray jsonArray = JSON.parseArray(dataStr);
        if (jsonArray == null && jsonArray.size() == 0) {
            return Result.error(HttpCodeEnum.RESULT_NULL.getCode(), HttpCodeEnum.RESULT_NULL.getMessage());
        }
        List<GarbageTypeResult> garbageTypeResults = jsonArray.toJavaList(GarbageTypeResult.class);
        // 保存识别结果到数据库
        if (Url.IS_SAVE) {
            try {
                saveResult(imgBase64Str, garbageTypeResults.toString());
            } catch (Exception e) {
                logger.error("保存识别结果到数据库异常", e);
            }
        }
        return Result.success(garbageTypeResults);
    }


    /**
     *  识别结果保存到数据库
     * @param base64
     * @param result
     */
    private void saveResult(String base64, String result) {
        GarbageType garbageType = new GarbageType();
        garbageType.setDistinguishResult(result);
        garbageType.setImageBase64(base64);
        garbageType.setDistinguishTime(new Date());
        int insert = garbageTypeMapper.insert(garbageType);
        if (insert > 0) {
            logger.info("保存数据库成功");
        }
    }

}
